iT邦幫忙

2022 iThome 鐵人賽

DAY 4
0
自我挑戰組

30天 Neetcode解題之路系列 第 4

Day 4 - 347. Top K Frequent Elements

  • 分享至 

  • xImage
  •  

前言

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
那就開始今天的解題吧~


Question

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.

Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

Think

給一個nums的陣列,找出其中出現次數前k名的。

用一個count_dict來存每個數字出現的字數,最後找出dictionary中values()最大值的index,再透過index找出對應的key值,重複這個步驟k次。

Code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        dict_s = {}
        dict_t = {}
        
        for index in range(len(s)):
            if s[index] in dict_s:
                dict_s[s[index]] += 1
            else:
                dict_s[s[index]] = 1
                
        for index in range(len(t)):    
            if t[index] in dict_t:
                dict_t[t[index]] += 1
            else:
                dict_t[t[index]] = 1
                
        return dict_s == dict_t

Submission


今天就到這邊啦~
大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 3 - 242. Valid Anagram
下一篇
Day 5 - 1. Two Sum
系列文
30天 Neetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言